package com.imooc.controller;

import com.alibaba.fastjson.JSON;
import com.imooc.common.dto.OrderDTO;
import com.imooc.common.enums.ResultEnum;
import com.imooc.common.exception.SelllException;
import com.imooc.service.OrderService;
import com.imooc.service.PayService;
import com.lly835.bestpay.model.PayResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.net.URLEncoder;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Controller
@RequestMapping("/pay")
public class PayController {

    @Autowired
    OrderService orderService;

    @Autowired
    PayService payService;

    @RequestMapping("/create")
    public ModelAndView create(@RequestParam("orderId") String orderId,
                               @RequestParam("returnUrl") String returnUrl,
                               Map<String, Object> params) {
        log.info("请求参数：orderId = {}， returnUrl = {}, params = {}", orderId, returnUrl, JSON.toJSONString(params));
        OrderDTO orderDTO = orderService.findOne(orderId);
        if (Objects.isNull(orderDTO)) {
            throw new SelllException(ResultEnum.ORDER_NOT_EXIST);
        }

        // 支付
        PayResponse payResponse = payService.create(orderDTO);

        params.put("payResponse", payResponse);
        params.put("returnUrl", returnUrl.startsWith("http://") ? returnUrl : URLEncoder.encode(returnUrl));

        log.info("返回params = {}", JSON.toJSONString(params));
        return new ModelAndView("pay/create", params);
    }

    @RequestMapping("/notify")
    public ModelAndView wechatNotify(@RequestBody String notifyData) {
        payService.wechatNotify(notifyData);

        // 返回微信处理结果
        return new ModelAndView("pay/success");
    }
}
